<template>
  <div class="header">
    <!-- 头部-面包屑 -->
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 主体 -->
    <div class="main">
      <!-- 头部搜索及按钮 -->
      <el-card>
        <el-row :gutter="16">
          <el-col :span="7">
            <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="queryUserList" @click="queryUserList">
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" icon="el-icon-add" @click="visible = true">添加用户</el-button>
          </el-col>
        </el-row>

        <!-- 表格 -->
        <el-table
          border
          :data="userList"
          stripe
          :header-cell-style="{color:'#000',fontSize:'14px',fontWeight:'blod'}">
          <el-table-column type="index"></el-table-column>
          <el-table-column label="姓名" prop="username"></el-table-column>
          <el-table-column label="邮箱" prop="email"></el-table-column>
          <el-table-column label="电话" prop="mobile"></el-table-column>
          <el-table-column label="角色" prop="role_name"></el-table-column>
          <el-table-column label="状态" prop="mg_state">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                active-color="#409EFF"
                @change="handleUserStatusChange(scope.row)"
                inactive-color="#ff4949">
              </el-switch>
              &nbsp;&nbsp;{{scope.row.mg_state?"启用":"停用"}}
            </template>
          </el-table-column>
          <!-- 手动给到特定长度 -->
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <el-button icon="el-icon-edit" type="primary" size="mini" @click="showEditUserDialog(scope.row)"></el-button>
              <el-button icon="el-icon-delete" type="danger" size="mini" @click="deleteUser(scope.row.id)"></el-button>
              <!-- enterable:鼠标是否可以点击到 -->
              <el-tooltip placement="top" content="分配用户角色" effect="light" :enterable="false">
                <!-- 分配角色 -->
                <el-button icon="el-icon-setting" type="warning" size="mini"  @click="setUserRoleShow(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[6,12,18,24]"
          :page-size="queryInfo.pagesize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange">
        </el-pagination>
      </el-card>

      <!-- 弹出框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="visible"
        width="50%"
        @close="close">
        <!-- 弹框主体 -->
        <el-form ref='addUser' label-width="70px" :model="addForm" :rules='addUserRules' status-icon>
          <el-form-item prop='username' label="用户名">
            <el-input v-model="addForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item prop='password' label="密码">
            <el-input v-model="addForm.password" type="password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item prop='email' label="邮箱">
            <el-input v-model="addForm.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item prop='mobile' label="手机 ">
            <el-input v-model="addForm.mobile" placeholder="请输入手机"></el-input>
          </el-form-item>
        </el-form>

        <!-- 底部按钮 -->
        <span slot="footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确认</el-button>
        </span>
      </el-dialog>

       <!-- 修改弹出框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="isShowEditUserDialog"
        width="50%"
        @close="closeEdit">
        <!-- 弹框主体 -->
        <el-form ref='editUser' label-width="70px" :model="editForm" :rules='editUserRules' status-icon>
          <el-form-item prop='username' label="用户名">
            <el-input v-model="editForm.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item prop='email' label="邮箱">
            <el-input v-model="editForm.email" type="email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item prop='mobile' label="手机 ">
            <el-input v-model="editForm.mobile" placeholder="请输入手机"></el-input>
          </el-form-item>
        </el-form>

        <!-- 底部按钮 -->
        <span slot="footer">
          <el-button @click="isShowEditUserDialog = false">取消</el-button>
          <el-button type="primary" @click="updateUser">确认</el-button>
        </span>
      </el-dialog>

      <!-- 展示分配角色的对话框 -->
      <el-dialog title="分配角色" :visible.sync="setRoleDialogShow" width="50%">
        <div>
          <p>当前的用户：{{userInfo.username}}</p>
          <p>当前的角色：{{userInfo.role_name}}</p>
          <p>分配新角色：
            <el-select clearable v-model="selectRoleId">
              <el-option v-for="i in rolesList" :key="i.id" :label="i.roleName" :value="i.id">
              </el-option>
            </el-select></p>
        </div>

        <span>
          <el-button @click="closeRoleDialog">取消</el-button>
          <el-button @click="confirmRoleBtn" type="primary">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getUserList, getALlRole } from '@/utils/https.js'
export default {
  data() {
    // 自定义规则-验证手机规则
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法手机'))
    }

    // 自定义规则-验证邮箱规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }

    return {
      setRoleDialogShow: false,
      userInfo: {},
      rolesList: [],
      selectRoleId: '',
      // 用户列表
      queryInfo: {
        query: '',
        pagenum: 1, // 当前页数
        pagesize: 6
      },
      userList: [],
      total: 0,
      isShowEditUserDialog: false,
      visible: false,
      addForm: {
        username: '',
        password: '',
        create_time: Date.now()
      },
      editForm: {},
      editUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 15, message: '名称长度在3-15个字之间', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: ['blur', 'change'] }],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }]
      },
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 15, message: '名称长度在3-15个字之间', trigger: 'blur' }],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度在6-12个字之间', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: ['blur', 'change'] }],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.queryUserList()
  },
  methods: {
    confirmRoleBtn() {
      if (!this.selectRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      this.$message.success('更新角色成功')
      this.queryUserList()
      this.closeRoleDialog()
    },
    closeRoleDialog() {
      this.selectRoleId = ''
      this.setRoleDialogShow = false
    },
    async setUserRoleShow(userData) {
      this.userInfo = userData
      const { data: res } = await getALlRole()
      this.rolesList = res.data.list
      // 在展示对话框前获取所有角色
      this.setRoleDialogShow = true
    },
    async deleteUser(id) {
      const confirmRes = await this.$confirm('此操作将永久删除该用户，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '算了',
        type: 'warning'
      }).catch(err => err) // 加了catch后才会返回字符串cancel

      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 删除用户根据id
      // 更新列表
      this.$message.success('删除成功')
    },
    showEditUserDialog(rowData) {
      // 根据id拿回用户信息，回显到输入框中
      this.editForm.username = rowData.username
      this.isShowEditUserDialog = true
    },
    updateUser() {
      // 表单预校验
      this.$refs.editUser.validate((vaildRes) => {
        if (!vaildRes) return
        this.isShowEditUserDialog = false
        // 发送后端请求 -> 更新用户
        // 刷新列表
        this.$message.success('更新用户成功')
      })
    },
    saveUser() {
      // 表单预校验
      this.$refs.addUser.validate((vaildRes) => {
        if (!vaildRes) return
        this.visible = false
        // 发送后端请求 -> 添加用户
        // 刷新列表
        this.$message.success('新增用户成功')
      })
    },
    // 关闭对话框
    closeEdit() {
      this.$refs.editUser.resetFields()
    },
    close() {
      this.$refs.addUser.resetFields()
    },
    handleUserStatusChange(row) {
      this.userList.forEach(i => {
        if (i.id === row.id) {
          i.ms_status = !i.ms_status
          this.$message.success('更新状态成功')
        }
      })
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.queryUserList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.queryUserList()
    },
    queryUserList() {
      getUserList(this.queryInfo).then(res => {
        if (res.data.data.status !== 200) {
          return this.$message.error('获取用户列表失败')
        }
        this.userList = res.data.data.users
        this.total = res.data.data.total
      }).catch(() => {
        this.$message.error('获取用户列表失败')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.iconfont .icon-add{
  font-size: 20px;
}
</style>
